package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.vo.Catelog2Vo;
import com.atguigu.gulimail.product.service.CategoryBrandRelationService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listwithtree() {
        List<CategoryEntity> categorys = baseMapper.selectList(null);

        List<CategoryEntity> level1 = categorys.stream().filter(
                CategoryEntity -> CategoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, categorys));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1;

    }

    @Override
    public void removeMenuByIds(List<Long> longs) {
        //TODO 删除前判断是否有引用
        baseMapper.deleteBatchIds(longs);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    /**
     * 更新级联属性
     */
    @Override
    @CacheEvict(value = {"category"} , key = "'getLevel1Categorys'")
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name") // 代表当前方法的结果需要缓存，如果缓存中有，方法不用调用。如果缓存中没有，就会调用方法，最后将方法的结果放入缓存
    // 每一个需要缓存的数据我们都来指定要放到那个名字的缓存。 【缓存的分区(按照业务类型分)】
    public List<CategoryEntity> getLevel1Categorys() {

        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntityList;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

        String catelogJSON = opsForValue.get("catelogJSON");
        if (StringUtils.isEmpty(catelogJSON)) {
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedisLock();
            return catelogJsonFromDb;
        }

        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    // 从数据库查询并封装数据

    /**
     * 作为 分布式锁，加锁与删锁都要是原子的，一个是 setIfAbSent 一个是Lua脚本。
     *
     * @return
     */
    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {

        //1、占分布式锁。去reids占坑。
//        String myUUID = UUID.randomUUID().toString();
        //自己写的锁
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", myUUID, 300L, TimeUnit.SECONDS);

        // 1、锁的名字-锁的粒度，越细越快
        RLock lock = redissonClient.getLock("CatelogJSON-lock");

        // 加锁成功
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
//                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            // 自己写得删除锁
//                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),myUUID);
        }

//            if (myUUID.equals(redisTemplate.opsForValue().get("lock"))){
//                redisTemplate.delete("lock");  //删除我自己的锁
//            }
        return dataFromDb;

    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        /**
         *  1、将数据库的多次查询变为1次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 1、查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1、每一个一级分类，查到这个一级分类的二级分类。
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            // 2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 3、查詢当前二级分类下的三级分类封装成Vo
                    List<CategoryEntity> level3Catelogs = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelogs != null) {

                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelogs.stream().map(l3 -> {
                            // 4、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCateglog3list(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));


        redisTemplate.opsForValue().set("catelogJSON", JSON.toJSONString(parent_cid));
        return parent_cid;
    }

    // 从数据库查询并封装数据
    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {

        synchronized (this) {
            // 得到锁以后，我们再去缓存中确定一次，如果没有才需要继续查询
            String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
            if (!StringUtils.isEmpty(catelogJSON)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }

            /**
             *  1、将数据库的多次查询变为1次
             */
            return getDataFromDb();
        }

    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    //递归查找所有路径
    public List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
        return paths;
    }

    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}